import datetime
import random

from django.shortcuts import render

# Create your views here.
import json
from django.http.response import JsonResponse

# 银行存管系统
# @app.route('/openb')
from db import DB


def openb(request):
    data = json.dumps(request.POST)
    data1 = json.loads(data)
    data11 = data1['imgs'][0]
    data12 = data1['imgs'][1]
    try:
        sql = "insert into open_an_account (name,age,id_number,id_front," \
              "id_reverse,user_id) values ('%s',%d,'%s','%s','%s',%d)" % (
                  data1['name'], int(data1['age']), data1['id_number'], data11,
                  data12, int(data1['user_id'])
              )
        db = DB()
        db.insert(sql)
        db.update("update user set account_one=1 where id=%d" % int(data1['user_id']))
        return JsonResponse({'code': 200})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 400})


from app.myqueue import myqueue
import time
import requests


# 银行审核结果
# @app.route('/bankaudit')
def bankaudit(request):
    state = request.GET.get('state')
    name = request.GET.get('name')
    # 调用p2p平台
    res = requests.get("http://localhost:5000/updateopen?state=" + str(state) + "&name=" + name)
    code = eval(res.text)
    print(code)
    if code['code'] != '200':
        print('2525')
        # 失败消息加入队列
        lst = {'count': 1, 'res': state, 'name': name}
        num = myqueue.sendmes('openbank', str(lst))
        print(num)
        requests.get('http://localhost:8000/mrecive/')
        return JsonResponse({'code': 405})
    else:
        pass
        return JsonResponse({'code': '200'})


import time


# @app.route('/mrecive')
def mrecive(request):
    myqueue.recivemes('openbank')


# 生成充值详情
def openb_bank(request):
    data = json.dumps(request.POST)
    data = json.loads(data)
    print(data['order_number'])
    db = DB()
    print(data)
    if str(data['card_number'][:6]) == '621098':
        db.update(
            "update china_bank set  money=money-%s where card_number='%s'" % (float(data['money']), data['ban_number']))
    dats = db.get_one("select * from user where id=%s" % data['userid'])
    db.update("update user set money=money+%s where id=%s" % (float(data['money']), int(data['userid'])))
    db.insert(
        "insert into order_details (order_number,ban_number,money,state,balance,userid,stats) values ('%s','%s',%d,1,%s,%s,2)" % (
            data['order_number'], data['ban_number'], float(data['money']), int(dats['money']), int(data['userid'])))
    return JsonResponse({'code': '200', 'msg': '充值成功'})


# 提现生成订单详情
def Withdrawal_details(request):
    data = json.dumps(request.POST)
    data = json.loads(data)
    print(data['order_number'])
    db = DB()
    print(data)
    dats = db.get_one("select * from user where id=%s" % data['userid'])
    money = dats['money'] - float(dats['money'])
    db.insert(
        "insert into order_details (order_number,ban_number,money,state,balance,userid,stats) values ('%s','%s',%s,2,%s,%s,1)" % (
            data['order_number'], data['ban_number'], float(data['money']), money, int(data['userid'])))
    # 减去账户中的余额
    print("update  user set money=money-%s where id=%s" % (float(data['money']), int(data['userid'])))
    db.update("update  user set money=money-%s where id=%s" % (float(data['money']), int(data['userid'])))
    # 往银行卡添加
    if str(data['ban_number'][:6]) == '621098':
        db.update(
            "update china_bank set  money=money+%s where card_number='%s'" % (float(data['money']), data['ban_number']))
    return JsonResponse({'code': '200', 'msg': '提现成功'})


def addcard(request):
    data = json.dumps(request.POST)
    data = json.loads(data)
    print(data)
    db = DB()
    if str(data['card_number'][:6]) == '621098':
        data = db.get_one("select * from china_bank where card_number='%s'" % (data['card_number']))
        if data:
            return JsonResponse(({'code': '200'}))
        else:
            return JsonResponse(({'code': '403', 'msg': '没此银行卡'}))
    else:
        return JsonResponse(({'code': '403', 'msg': '此银行没合作'}))


# 添加基金订单实时获取
def add_bank_fund(request):
    # data = json.dumps(request.POST)
    data = request.POST
    print(data['name'])
    db = DB()
    time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d 00:00:00')
    # if int(data['time_state'])==1:
    data1 = db.get_one("select * from china_fund where name ='%s'" % data['name'])
    if data1:
        db.update("update china_fund set stauts=2 where name='%s' and stauts=1" % data['name'])
        if int(data['time_state']) == 2:
            print('111')
            shishi_data = db.get_all("select * from my_fund where  china_funt='%s'" % data['name'])
            for i in shishi_data:
                money_one = db.get_one("select * from my_fund where id=%s" % i['id'])
                money = float(money_one['money']) % float(data['interest_rate'])
                print(money)
                db.update("update my_fund set money=money+(money*%s) where id=%s" % (data['interest_rate'], i['id']))

    if int(data['time_state']) == 1:
        db.update(
            "insert into china_fund (name,model,stating_amount,interest_rate,state,add_time,time_state) values ('%s','%s',%s,%s,%s,'%s',%s)" %
            (data['name'], data['model'],
             float(data['stating_amount']),
             float(data['interest_rate']), int(data['state']), time, int(data['time_state'])))
        send(int(data['time_state']))
    if int(data['time_state']) == 2:
        db.insert(
            "insert into china_fund (name,model,stating_amount,interest_rate,time_state,add_time) values ('%s','%s',%s,%s,%s,'%s')" %
            (data['name'], data['model'], data['stating_amount'],
             float(data['interest_rate']), data['time_state'], time))
        send(int(data['time_state']))
    # if int(data['time_state']) == 3:
    #     db.insert(
    #         "insert into china_fund (name,model,stating_amount,interest_rate,time_state,add_time) values ('%s','%s',%s,%s,%s,'%s')" %
    #         (data['name'], data['model'], data['stating_amount'],
    #          float(data['interest_rate']), data['time_state'], time))
    #     send(int(data['time_state']))
    return JsonResponse({'code': '200', 'msg': '添加订单'})


# 获取基金
def get_bank_fund(request):
    datas = request.POST
    print(datas['nuid'])
    db = DB()
    data = db.get_all("select * from china_fund where stauts=1 and time_state=%s" % int(datas['nuid']))
    if int(datas['nuid']) == 3:
        for i in data:
            print(i)
            data2 = db.get_one("select * from day_calculation where name='%s' and state=1" % i['name'])
            if data2:
                i['name'] = data2['name']
                i['interest_rate'] = data2['interest_rate']
                i['add_time'] = data2['datetime']
    return JsonResponse({'code': '200', 'list': data})


def my_fund_get(request):
    data = request.POST
    db = DB()
    data = db.get_all(
        "select * from my_fund  inner join china_fund  on bank_id=china_fund.id where userid=%s and time_state=%s" % (
        data['userid'], data['nuid']))

    return JsonResponse({'code': '200', 'list': data})


# 卖出
def sell_out(request):
    data = request.POST
    db = DB()
    db.update("update my_fund set money=money-%s where id=%s" % (data['price'], data['nu_di']))
    num = random.randint(1000, 9999)
    order_number = str(datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d%H%M%S')) + str(num)
    res_moneys = db.find("select * from my_fund where id=%d" % int(data['nu_di']))
    sql4 = "update user set money=money+%s where id=%d" % (
        float(data['price']), int(res_moneys['userid']))
    db.update(sql4)
    res_money = db.find("select * from user where id=%d" % int(res_moneys['userid']))
    db.insert(
        "insert into order_details (order_number,money,state,balance,userid,stats) values ('%s',%s,9,%s,%s,1)" % (
            order_number, data['price'], res_money['money'], int(res_moneys['userid'])))
    return JsonResponse({'code': '200'})


# 添加第三类基金 按天计算

def day_calculation(request):
    data = request.POST
    db = DB()
    time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d 00:00:00')
    # if int(data['time_state'])==1:
    data1 = db.get_one("select * from china_fund where name ='%s'" % data['name'])
    if data1:
        data2 = db.get_all("select * from day_calculation where name='%s'" % data['name'])
        for i in data2:
            db.update("update day_calculation set state=2 where id=%s" % i['id'])
        db.insert("insert into day_calculation (name,interest_rate,datetime,fund_id) values ('%s',%s,'%s',%s)" % (
        data['name'], data['interest_rate'], time, data1['id']))
        send(3)
        return JsonResponse({'code': '200'})
    else:
        db.insert(
            "insert into china_fund (name,model,stating_amount,interest_rate,time_state,add_time) values ('%s','%s',%s,%s,%s,'%s')" %
            (data['name'], data['model'], data['stating_amount'],
             float(data['interest_rate']), data['time_state'], time))
        db.insert("insert into day_calculation (name,interest_rate,datetime,fund_id) values ('%s',%s,'%s',%s)" % (
        data['name'], data['interest_rate'], time, data1['id']))
        send(int(data['time_state']))
    send(3)
    return JsonResponse({'code': '200'})


# 购买第三类基金
def thina_fund(request):
    data = request.POST
    print(data)
    db = DB()
    datae = db.get_one("select * from user where id=%s and pay_password=%s" % (data['userid'], data['password']))
    num = random.randint(1000, 9999)
    order_number = str(datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d%H%M%S')) + str(num)
    add_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d 00:00:00')
    day = data['days']
    end_time = (datetime.datetime.now() - datetime.timedelta(days=-int(day))).strftime("%Y-%m-%d 00:00:00")
    num_ors = db.get_one("select * from china_fund where id=%s" % int(data['num_id']))
    if float(num_ors['stating_amount']) > float(data['price']):
        return JsonResponse({'code': 403, 'msg': '购买资金不能低于%s' % num_ors['stating_amount']})
    num_or = db.get_one("select * from day_calculation where fund_id=%s and state=1" % int(data['num_id']))
    print(num_or)
    if datae:
        status = 5
        db.insert(
            "insert into my_fund (order_number,bank_id,china_funt,status,add_time,end_time,input_time,money,userid)"
            " values ('%s',%s,'%s',%s,'%s','%s',%s,%s,%s)" % (
                order_number, int(data['num_id']), num_or['name'], status, add_time, end_time, data['days'],
                float(data['price']),
                int(data['userid'])))
        return JsonResponse({'code': '200', 'msg': '购买成功'})
    else:
        return JsonResponse({'code': 403, 'msg': '支付密码错误'})


from dwebsocket.decorators import accept_websocket
from django.http import HttpResponse, JsonResponse
import json

# 存储连接websocket的用户
websocketlist = []


@accept_websocket
def websocketLink(request):
    # 获取连接
    if request.is_websocket:
        # 新增 用户  连接信息
        websocketlist.append(request.websocket)
        # 监听接收客户端发送的消息 或者 客户端断开连接
        for message in request.websocket:
            break


# 发送消息
def websocketMsg(client, msg):
    b1 = json.dumps(msg, ensure_ascii=False).encode('utf-8')
    client.send(b1)


import time


# 服务端发送消息
def send(id):
    if websocketlist:
        for i in websocketlist:
            db = DB()
            mes = db.get_all("select * from china_fund where stauts=1 and time_state=%s" % id)
            if int(id) == 3:
                for j in mes:
                    data2 = db.get_one("select * from day_calculation where name='%s' and state=1" % j['name'])
                    if data2:
                        j['name'] = data2['name']
                        j['interest_rate'] = data2['interest_rate']
                        j['add_time'] = data2['datetime']
            b1 = json.dumps(mes, ensure_ascii=False).encode('utf-8')
            i.send(b1)
    return HttpResponse("ok")


# 定时任务向前端发送任务 可舍弃
from apscheduler.schedulers.background import BackgroundScheduler

# 按天运算
def testap(request):
    # 调度器
    scheduler = BackgroundScheduler()
    # 任务存储   seconds 每秒动用多少次
    scheduler.add_job(Timing_details, 'interval', minutes=1,start_date='2022-2-15 19:35:00', end_date='2022-2-17 11:00:00')
    scheduler.start()
    return HttpResponse("ok")


def Timing_details():
    db = DB()
    data = db.get_all("select * from my_fund where status=5")
    for i in data:
        # 前一天时间/
        now_time = (datetime.datetime.now() - datetime.timedelta(days=+1)).strftime("%Y-%m-%d 00:00:00")
        dt = datetime.datetime.strptime(now_time, '%Y-%m-%d %H:%M:%S')
        if i['end_time'] > dt or i['add_time'] <= dt:
            data_all = db.get_all(
                "select * from china_fund inner join day_calculation on china_fund.id=day_calculation.fund_id where china_fund.id=%s and china_fund.name='%s' and day_calculation.datetime='%s'" % (
                i['bank_id'], i['china_funt'], dt))
            print(data_all)
            for j in data_all:
                profit = i['money'] * j['day_calculation.interest_rate']
                interest_rate = j['day_calculation.interest_rate']
                userid = i['userid']
                mu_fund_id = j['id']
                money = float(i['money'])+ float((i['money'] * j['day_calculation.interest_rate']))
                bank_fund_id = i['bank_id']
                db.insert(
                    "insert into deteils_time (bank_fund_id,date_time,profit,money,interest_rate,userid,mu_fund_id) "
                    "values (%s,'%s',%s,%s,%s,%s,%s)" % (bank_fund_id,dt,
                                                         float(profit),float(money),interest_rate,userid,int(mu_fund_id)))

        if i['end_time'] == dt:
            data_all = db.get_all(
                "select * from china_fund inner join day_calculation on china_fund.id=day_calculation.fund_id where china_fund.id=%s and china_fund.name='%s' and day_calculation.datetime='%s'" % (
                    i['bank_id'], i['china_funt'], dt))
            for j in data_all:
                profit = i['money'] * j['day_calculation.interest_rate']
                interest_rate = j['day_calculation.interest_rate']
                userid = i['userid']
                mu_fund_id = j['id']
                money = float(i['money']) + float((i['money'] * j['day_calculation.interest_rate']))
                bank_fund_id = i['bank_id']
                db.insert(
                    "insert into deteils_time (bank_fund_id,date_time,profit,money,interest_rate,userid,mu_fund_id) "
                    "values (%s,'%s',%s,%s,%s,%s,%s)" % (bank_fund_id, dt,
                                                         float(profit), float(money), interest_rate, userid,
                                                         int(mu_fund_id)))
            db.update("update my_fund set status=6 where id=%s" % (i['id']))

    return 'ok'


def get_eachart(request):
    data=request.GET
    db=DB()
    date_list=[]
    interest_list=[]
    data_all = db.get_all(
        "select datetime,day_calculation.interest_rate from china_fund inner join day_calculation on china_fund.id=day_calculation.fund_id where china_fund.id=%s and china_fund.name='%s'" % (
            data['echart_id'], data['echart_name']))
    print(data_all)
    for i in data_all:
        if i['datetime']:
            date_list.append(i['datetime'])
            interest_list.append(i['interest_rate'])

    print(date_list)
    print(interest_list)
    return JsonResponse({'code':200,'date_list':date_list,'interest_list':interest_list})






